"""
检查数据库中的refresh tokens
"""
import sys
sys.path.append('.')

from database import SessionLocal
from models import RefreshToken

def check_refresh_tokens():
    """检查数据库中的refresh tokens"""
    print("=== 检查数据库中的refresh tokens ===")
    
    db = SessionLocal()
    
    try:
        # 获取所有refresh token记录
        all_tokens = db.query(RefreshToken).order_by(RefreshToken.created_at.desc()).limit(10).all()
        
        print(f"\n数据库中最近的 {len(all_tokens)} 个refresh token记录:")
        
        for i, token in enumerate(all_tokens, 1):
            print(f"{i}. Token: {token.token[:50]}...")
            print(f"   User ID: {token.user_id}")
            print(f"   Created: {token.created_at}")
            print(f"   Expires: {token.expires_at}")
            print(f"   Is Revoked: {token.is_revoked}")
            print("")
        
        # 检查是否有重复的token
        token_counts = {}
        for token in all_tokens:
            if token.token in token_counts:
                token_counts[token.token] += 1
            else:
                token_counts[token.token] = 1
        
        duplicates = {token: count for token, count in token_counts.items() if count > 1}
        
        if duplicates:
            print(f"❌ 发现重复的tokens: {len(duplicates)}个")
            for token, count in duplicates.items():
                print(f"   Token: {token[:50]}..., 出现次数: {count}")
        else:
            print("✅ 没有发现重复的tokens")
            
        # 检查特定token
        test_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkZWJ1Z191c2VyXzAxMDI0NyIsImV4cCI6MTc2NTEyNjk2NywidHlwZSI6InJlZnJlc2gifQ.YqGcvPlmDojLaxDgZ5AiQ3wFTMTpIo0Vr3YsgtjbJio"
        existing_token = db.query(RefreshToken).filter(RefreshToken.token == test_token).first()
        
        if existing_token:
            print(f"\n✅ 在数据库中找到测试token")
            print(f"   User ID: {existing_token.user_id}")
            print(f"   Is Revoked: {existing_token.is_revoked}")
            print(f"   Created: {existing_token.created_at}")
        else:
            print(f"\n❌ 数据库中未找到测试token")
        
    except Exception as e:
        print(f"❌ 检查过程中出现异常: {e}")
        import traceback
        traceback.print_exc()
        
    finally:
        db.close()

if __name__ == "__main__":
    check_refresh_tokens()